import os
from datetime import datetime

from PIL import Image
from reportlab.pdfgen import canvas


def image_to_pdf(image_path, pdf_folder, pdf_filename=None, mask='auto', page_margin=(0, 0)):
    try:
        # 确保路径存在
        if not os.path.exists(pdf_folder):
            os.mkdir(pdf_folder)

        # 使用给定的文件名或当前时间戳作为PDF文件名
        if pdf_filename is None:
            pdf_filename = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
        pdf_path = os.path.join(pdf_folder, f"{pdf_filename}.pdf")

        # 打开图片
        image = Image.open(image_path)

        # 获取图片的尺寸
        image_width, image_height = image.size

        # 解包页边距
        left_margin, top_margin = page_margin

        # 计算PDF页面的大小
        page_width = image_width + left_margin * 2
        page_height = image_height + top_margin * 2
        c = canvas.Canvas(pdf_path, pagesize=(page_width, page_height))

        # 计算图像绘制的位置
        x_position = left_margin
        y_position = top_margin

        # 将图片绘制到PDF页面上
        c.drawImage(image_path, x_position, y_position, width=image_width, height=image_height, mask=mask)
        c.showPage()
        c.save()
    except FileNotFoundError:
        print("[Error] The image does not exist")
        return "[Error] The image does not exist"
    except Exception as e:
        print(f"[Error] {e}")
        return f"[Error] {e}"


if __name__ == '__main__':
    image_path = "images/yes.png"
    pdf_folder = "PDF/"

    image_to_pdf(image_path, pdf_folder, 'yes', page_margin=(50, 50))
